package myDaos;

import java.util.Date;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import model.entities.ChubConsStocksInfo;

@Stateless
public class ChubStocksDao {
	@PersistenceContext(unitName = "UnileverProcedure")
    private EntityManager em;
	
	public EntityManager getEntityManager() {
        return em;
    }
	
	public List<ChubConsStocksInfo> getAllStocks(String distributor,String country,Date from,Date to){
		List<ChubConsStocksInfo> sList= null;
		try{
			StringBuffer queryBiffer = new StringBuffer();
			queryBiffer.append(" SELECT s FROM ChubConsStocksInfo s WHERE 1=1 "); 
		    	
			if(distributor!=null && !distributor.trim().equals(""))
    	    {
				queryBiffer.append(" and s.distributorNo IN (:distributor)") ;	
    	    }
			
			if(country!=null && !country.trim().equals(""))
    	    {
				queryBiffer.append(" AND s.country = :country") ;	
    	    }

			if(from!=null)
    	    {
				queryBiffer.append("  AND trunc(s.stkDate) >= trunc(:fDate)") ;	
    	    }

			if(to!=null)
    	    {
				queryBiffer.append("  AND trunc(s.stkDate) <= trunc(:tDate)") ;	
    	    }
			
			if(from == null )
    	    {
				queryBiffer.append("  AND trunc(s.stkDate) >= trunc(sysdate)-30") ;	
    	    }
			
			Query q = getEntityManager().createQuery(queryBiffer.toString());

			if(distributor!=null && !distributor.trim().equals("")){q.setParameter("distributor",distributor);} 
			if(country!=null && !country.trim().equals("")){q.setParameter("country", country);}
			if(from!=null){q.setParameter("fDate", from);}
			if(to!=null){q.setParameter("tDate", to);}
			
			sList = q.getResultList();
			
		}
		catch(Exception e){
			e.printStackTrace();
		}
		return sList;
	}
}
